package com.szly.phm.admin.security;

import com.alibaba.fastjson.JSONObject;
import com.szly.phm.common.entity.result.CodeStatusEnum;
import com.szly.phm.common.entity.vo.UserVO;
import com.szly.phm.common.utils.BeanCopyUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description : ${创建类}
 * @Author : chengjiang
 * @Date: 2021/7/2 16:48
 */
@Component
public class JEJLLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        var loginUser = (LoginUser) authentication.getPrincipal();
        var userVO = new UserVO();
        if (loginUser != null) {
            userVO.setToken(loginUser.getToken());
            userVO.setUsername(loginUser.getUsername());
            userVO.setUserPermissions(loginUser.getUserPermissions());
            if (loginUser != null) {
                BeanCopyUtils.copy(loginUser, userVO);
            }
        }
        var jsonObject = new JSONObject();
        jsonObject.put("code", CodeStatusEnum.SUCCESS.getCode());
        jsonObject.put("message", CodeStatusEnum.SUCCESS.getMessage());
        jsonObject.put("data", userVO);
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().write(jsonObject.toJSONString());
    }
}
